package com.runa.protocol.analysis;

import com.runa.protocol.dto.DtuReport;
import com.runa.protocol.dto.IInterData;
import com.runa.protocol.util.ByteUtil;

public class DtuCMBufferAnalysis extends ShellBufferAnalysis<byte[]> {

    //选择是用哪个作为标识，0：设备ID，1：电话号码
    private int select;

    public DtuCMBufferAnalysis(MetaBufferAnalysis analysis, int select) {
        super(analysis, 128);
        this.select = select;
    }

    @Override
    public int fill(byte[] data, int length,String n) {
        switch (select) {
            case 0:
                return selectHandle0(data, length);
            case 1:
                return selectHandle1(data, length);
        }
        return 0;
    }

    private int selectHandle0(byte[] data, int length) {
        if (netEquNo == null) {
            if (length < 21) {
                return -1;
            }
            netEquNo = ByteUtil.bcd2str(data, 0, 4, false);
            String phoneNumber = ByteUtil.byteToHexString(data, 4, 11);
            String ip = (data[16] & 0xff) + "." +
                    (data[17] & 0xff) + "." + (data[18] & 0xff) + "." + (data[19] & 0xff);
            interData = new DtuReport(netEquNo);
            return length - 21;
        } else if (data[0] == (byte) 0xfe){
            interData = new DtuReport(netEquNo);
            return length - 1;
        } else {
            if (length > buffer.length) {
                expand(length);
            }
            int cnt = 0;
            for (int i=0; i<length; i++) {
                if (data[i] == (byte) 0xfd && data[i+1] == (byte) 0xed) {
                    buffer[cnt++] = (byte) 0xfd;
                    i++;
                } else if (data[i] == (byte) 0xfd && data[i+1] == (byte) 0xee) {
                    buffer[cnt++] = (byte) 0xfe;
                    i++;
                } else {
                    buffer[cnt++] = data[i];
                }
            }
            int ret = analysis.fill(buffer, cnt,netEquNo);
            interData = analysis.gain();
            return ret;
        }
    }

    private int selectHandle1(byte[] data, int length) {
        if (netEquNo == null) {
            if (length < 21) {
                return -1;
            }
            if (data[15] == 0) {
                netEquNo = new String(data, 4, 11);
                String ip = (data[16] & 0xff) + "." +
                        (data[17] & 0xff) + "." + (data[18] & 0xff) + "." + (data[19] & 0xff);
                interData = new DtuReport(netEquNo);
            }
            return length - 21;
        } else if (netEquNo.equals(new String(data, 4, 11))){
            interData = new DtuReport(netEquNo);
            return length - 21;
        } else {
            int ret = analysis.fill(data, length,netEquNo);
            interData = analysis.gain();
            return ret;
        }
    }

}
